package controllers

import (
	"encoding/json"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"

	"github.com/beego/beego/v2/server/web"
)

// MiniMemberRechargeController 处理小程序会员充值相关请求
type MiniMemberRechargeController struct {
	web.Controller
}

// Create 创建充值订单
func (c *MiniMemberRechargeController) Create() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析JSON请求体
	var requestData struct {
		PackageId int64   `json:"package_id"`
		Amount    float64 `json:"amount"`
		Type      int8    `json:"type"`
		StoreId   int64   `json:"store_id"`
	}

	// 解析JSON数据
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "解析请求数据失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	var packageId int64 = requestData.PackageId
	var amount float64
	var giftAmount float64
	var giftPoints int
	var rechargeType int8
	var storeId int64
	var description string

	if packageId > 0 {
		// 使用充值套餐
		pkg, err := models.GetRechargePackageById(packageId)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "套餐不存在: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		if pkg.Status != 1 || pkg.IsDeleted == 1 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "套餐不可用",
			}
			c.ServeJSON()
			return
		}

		// 使用套餐信息
		amount = pkg.Amount
		giftAmount = pkg.GiftAmount
		giftPoints = pkg.GiftPoints
		rechargeType = pkg.Type
		storeId = pkg.StoreId
		description = pkg.Name
	} else {
		// 自定义金额充值
		amount = requestData.Amount
		if amount <= 0 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "充值金额无效",
			}
			c.ServeJSON()
			return
		}

		rechargeType = requestData.Type
		if rechargeType != 1 && rechargeType != 2 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "充值类型无效",
			}
			c.ServeJSON()
			return
		}

		storeId = requestData.StoreId
		if rechargeType == 2 && storeId <= 0 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "门店ID无效",
			}
			c.ServeJSON()
			return
		}

		description = "会员充值"
	}

	// 创建充值记录
	record := &models.RechargeRecord{
		MemberId:    member.Id,
		Amount:      amount,
		Type:        rechargeType,
		PackageId:   packageId,
		PayMethod:   "wechat",
		StoreId:     storeId,
		Description: description,
	}

	_, err = models.CreateRechargeRecord(record)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建充值订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取充值记录
	record, err = models.GetRechargeRecordByOrderNo(record.OrderNo)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 生成支付参数 - 需要获取用户的openId
	// 从会员信息中获取openId，如果没有则使用空字符串
	openId := ""
	if member.OpenId != "" {
		openId = member.OpenId
	}

	payParams, err := utils.GenerateWxPayParams(member.FranchiseId, record.OrderNo, int64(amount*100), description, openId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "生成支付参数失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建充值订单成功",
		"data": map[string]interface{}{
			"order_no":    record.OrderNo,
			"amount":      amount,
			"gift_amount": giftAmount,
			"gift_points": giftPoints,
			"package_id":  packageId,
			"pay_params":  payParams,
		},
	}
	c.ServeJSON()
}

// List 获取充值记录列表
func (c *MiniMemberRechargeController) List() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 获取充值记录列表
	records, total, err := models.GetMemberRechargeRecords(member.Id, page, pageSize, member.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取充值记录成功",
		"data": map[string]interface{}{
			"list":  records,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// Notify 支付回调通知
func (c *MiniMemberRechargeController) Notify() {
	// 解析支付回调数据
	notifyData, err := utils.ParseWxPayNotify(c.Ctx.Input.RequestBody)
	if err != nil {
		c.Data["xml"] = utils.GenerateWxPayNotifyResponse("FAIL", "解析回调数据失败")
		c.ServeXML()
		return
	}

	// 验证签名
	_, err = utils.VerifyWxPayNotify(0, c.Ctx.Input.RequestBody)
	if err != nil {
		c.Data["xml"] = utils.GenerateWxPayNotifyResponse("FAIL", "签名验证失败")
		c.ServeXML()
		return
	}

	// 获取充值记录
	record, err := models.GetRechargeRecordByOrderNo(notifyData.OutTradeNo)
	if err != nil {
		c.Data["xml"] = utils.GenerateWxPayNotifyResponse("FAIL", "获取充值记录失败")
		c.ServeXML()
		return
	}

	// 更新充值记录状态
	err = models.UpdateRechargeStatus(record.OrderNo, 1, "wechat", notifyData.TransactionId)
	if err != nil {
		c.Data["xml"] = utils.GenerateWxPayNotifyResponse("FAIL", "更新充值记录失败")
		c.ServeXML()
		return
	}

	// 更新会员余额
	err = models.UpdateMemberBalanceWithBonus(record.MemberId, record.Amount, record.GiftAmount, record.GiftPoints)
	if err != nil {
		c.Data["xml"] = utils.GenerateWxPayNotifyResponse("FAIL", "更新会员余额失败")
		c.ServeXML()
		return
	}

	c.Data["xml"] = utils.GenerateWxPayNotifyResponse("SUCCESS", "OK")
	c.ServeXML()
}
